package readers;

import org.apache.log4j.Logger;
import org.supercsv.io.CsvListReader;

import java.util.List;
import java.util.ArrayList;
import java.io.IOException;

import jxl.Workbook;
import jxl.Cell;
import jxl.Sheet;

public class ExcelRowReader implements RowReader {
    private final Workbook w;
    private final Sheet sh;
    private Cell[] headers;

    private int rowNumber = 0;

    public ExcelRowReader(Workbook w) throws IOException {
        this.w = w;
        this.sh = w.getSheet(0);
        headers = sh.getRow(rowNumber++);
    }

    public List<String> read() throws Exception {
        if(rowNumber >= sh.getRows()) {
            return null;
        }

        Cell[] row = sh.getRow(rowNumber++);
        List<String> result = new ArrayList<String>(row.length);
        for(Cell c : row) {
            result.add(c.getContents());
        }
        return result;
    }

    public void printHeader(Logger log) {
        int i = 0;
        log.debug("workbook " + w.getSheetNames()[0]);
        for(Cell header : headers) {
            log.debug(" with header field ["+ (i++) + "]: " + header.getContents());
        }
    }

    public void close() throws Exception {
        w.close();
    }
}